package com.chen.file.controller;

import cn.hutool.core.lang.Assert;
import com.chen.base.utils.file.IoFileUtil;
import com.chen.file.params.FileSplitDownloadParam;
import com.chen.file.params.FileSplitUploadParam;
import com.chen.file.service.FileService;
import com.chen.file.vo.FileInfoVO;
import com.chen.root.base.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.io.File;

/**
 * 文件上传下载
 * @author: Long
 * @date: 2023/8/9 22:34
 **/
@RestController
@RequestMapping("/file")
@Validated
@Api(value = "file",tags = "文件上传下载API")
public class FileController {

    @Resource
    private FileService fileService;

    @PostMapping("/info")
    @ApiOperation(value = "文件基本属性",notes = "文件基本属性")
    public R<FileInfoVO> fileInfo(@NotBlank(message = "文件路径不能为空") String filePath){
        File file = new File(filePath);
        Assert.isTrue(file.exists() && file.isFile(),"文件不存在，请检查文件路径！");
        return R.ok(new FileInfoVO(file.length(), IoFileUtil.md5(filePath), file.getName()));
    }

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传",notes = "文件上传")
    public R<String> uploadFile(MultipartFile multiFile){
        String filePath = fileService.uploadFile(multiFile);
        return R.ok(filePath,"上传成功");
    }

    @PostMapping("/splitUpload")
    @ApiOperation(value = "文件分片上传",notes = "文件分片上传")
    public R<String> fileSplitUpload(@Validated FileSplitUploadParam param) {
        String filePath = fileService.fileSplitUpload(param);
        return R.ok(filePath);
    }

    @PostMapping("/download")
    @ApiOperation(value = "文件下载",notes = "文件下载")
    public void downloadFile(@NotBlank(message = "文件路径不能为空") String filePath) {
        fileService.downloadFile(filePath);
    }

    @PostMapping("/splitDownload")
    @ApiOperation(value = "文件分片下载",notes = "文件分片下载")
    public void fileSplitDownload(@Validated FileSplitDownloadParam param) {
        fileService.fileSplitDownload(param);
    }
}
